// 全局状态
let currentChart = null;
let isProcessing = false;
let abortController = null;

// DOM元素
const queryInput = document.getElementById('queryInput');
const executeBtn = document.getElementById('executeBtn');
const chartContainer = document.getElementById('chartContainer');
const chartPlaceholder = document.getElementById('chartPlaceholder');
const summaryArea = document.getElementById('summaryArea');
const errorArea = document.getElementById('errorArea');
const loadingIndicator = document.querySelector('.loading');
const connectionStatus = document.getElementById('connectionStatus');
const lastUpdate = document.getElementById('lastUpdate');
const currentDate = document.getElementById('currentDate');
const chartStatus = document.getElementById('chartStatus');
const debugArea = document.getElementById('debugArea');

// 配置 marked
marked.setOptions({
    breaks: true,
    gfm: true,
    tables: true
});

// 初始化页面
document.addEventListener('DOMContentLoaded', function () {
    // 设置当前日期
    currentDate.textContent = new Date().toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric'
    });

    // 绑定事件
    executeBtn.addEventListener('click', executeAnalysis);
    queryInput.addEventListener('keypress', e => e.key === 'Enter' && executeAnalysis());

    // 示例按钮事件
    document.querySelectorAll('.example-btn').forEach(btn => {
        btn.addEventListener('click', function () {
            queryInput.value = this.textContent;
            executeAnalysis();
        });
    });

    updateChartStatus('等待查询...', '#666');
    addDebugInfo('系统就绪');
});

// 执行分析
async function executeAnalysis() {
    if (isProcessing) {
        showError('正在处理上一个请求，请稍候...');
        return;
    }

    const query = queryInput.value.trim();
    if (!query) {
        showError('请输入查询内容');
        return;
    }

    // 取消之前的请求
    if (abortController) {
        abortController.abort();
    }

    // 重置状态
    isProcessing = true;
    abortController = new AbortController();
    showLoading(true);
    clearError();
    clearChart();
    clearDebug();

    summaryArea.innerHTML = '<h3>分析中...</h3><p>正在处理您的查询，请稍候</p>';

    // 更新连接状态
    connectionStatus.textContent = '连接中...';
    connectionStatus.style.color = '#f39c12';
    updateChartStatus('正在连接服务器...', '#f39c12');
    addDebugInfo(`开始分析: ${query}`);

    try {
        const response = await fetch('/api/ai/analyze', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({query, chartType: 'auto'}),
            signal: abortController.signal
        });

        if (!response.ok) throw new Error(`HTTP错误: ${response.status}`);

        connectionStatus.textContent = '已连接';
        connectionStatus.style.color = '#2ecc71';
        updateChartStatus('已连接，正在处理...', '#2ecc71');
        addDebugInfo('服务器连接成功');

        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let buffer = '';

        while (true) {
            const {done, value} = await reader.read();
            if (done) break;

            buffer += decoder.decode(value, {stream: true});
            const lines = buffer.split('\n');
            buffer = lines.pop() || '';

            for (const line of lines) {
                if (line.startsWith('data:')) {
                    const eventData = line.substring(5).trim();
                    if (eventData) {
                        try {
                            processEvent(JSON.parse(eventData));
                        } catch (e) {
                            console.error('解析事件失败:', e);
                        }
                    }
                }
            }
        }

        isProcessing = false;
        showLoading(false);
        addDebugInfo('分析完成');

    } catch (error) {
        if (error.name === 'AbortError') {
            addDebugInfo('请求已取消');
            return;
        }

        console.error('请求失败:', error);
        showError('请求失败: ' + error.message);
        addDebugInfo(`请求失败: ${error.message}`);

        connectionStatus.textContent = '已断开';
        connectionStatus.style.color = '#e74c3c';
        updateChartStatus('连接失败', '#e74c3c');

        isProcessing = false;
        showLoading(false);
    }
}

// 处理事件
function processEvent(data) {
    addDebugInfo(`${data.type}: ${data.message || data.step}`);

    switch (data.type) {
        case 'chart':
            updateChartStatus('图表已生成', '#2ecc71');
            renderChart(data.data);
            showLoading(false);
            break;
        case 'summary_chunk':
            //updateChartStatus('生成分析中...', '#3498db');
            appendSummaryChunk(data.data);
            break;
        case 'summary_complete':
            updateChartStatus('分析完成', '#2ecc71');
            completeSummary(data.data);
            break;
        case 'error':
            updateChartStatus('处理出错', '#e74c3c');
            showError(data.message);
            showLoading(false);
            break;
        case 'status':
            updateChartStatus(data.message, '#3498db');
            break;
        case 'sql':
            updateChartStatus('SQL生成完成', '#3498db');
            break;
        case 'data':
            updateChartStatus('数据查询完成', '#3498db');
            break;
    }

    lastUpdate.textContent = new Date().toLocaleTimeString();
}

// 渲染图表
function renderChart(config) {
    if (!config) return;

    chartPlaceholder.style.display = 'none';
    chartContainer.style.display = 'block';

    const chart = echarts.init(chartContainer);

    try {
        const option = buildEChartsOption(config);
        chart.setOption(option);
        window.addEventListener('resize', () => chart.resize());
        addDebugInfo('图表渲染成功');
    } catch (error) {
        console.error('图表渲染失败:', error);
        showError('图表渲染失败');
        chartPlaceholder.style.display = 'flex';
        chartContainer.style.display = 'none';
    }
}

// 构建ECharts配置
function buildEChartsOption(chartConfig) {
    const baseOption = {
        title: {text: '数据分析图表', left: 'center'},
        tooltip: {trigger: 'axis'},
        grid: {left: '50px', right: '50px', bottom: '50px', top: '60px'}
    };

    if (typeof chartConfig === 'string') {
        try {
            chartConfig = JSON.parse(chartConfig);
        } catch (e) {
            return baseOption;
        }
    }

    return {...baseOption, ...chartConfig};
}

// 追加分析内容
function appendSummaryChunk(chunkData) {
    const fullContent = chunkData.fullContent || '';

    if (fullContent.trim()) {
        const markdownFormat = fixMarkdownFormat(fullContent);
        const htmlContent = marked.parse(markdownFormat);

        summaryArea.innerHTML = `
            <div class="markdown-content">${htmlContent}</div>
            <div class="streaming-indicator">
                <div class="typing-animation">
                    <span></span><span></span><span></span>
                </div>
                <span>AI正在思考中...</span>
            </div>
        `;
        summaryArea.scrollTop = summaryArea.scrollHeight;
    }
}

// 完成分析总结
function completeSummary(completeData) {
    const fullContent = completeData.fullContent || '';
    if (fullContent.trim()) {
        const markdownFormat = fixMarkdownFormat(fullContent);
        const htmlContent = marked.parse(markdownFormat);

        summaryArea.innerHTML = `
            <div class="markdown-content">${htmlContent}</div>
            <div style="margin-top: 20px; padding-top: 15px; border-top: 1px dashed #eee; color: #7f8c8d; font-size: 14px;">
                <i>提示：以上分析由AI生成，仅供参考</i>
            </div>
        `;
    }

    showLoading(false);
    summaryArea.scrollTop = summaryArea.scrollHeight;
}

/**
 * MD文档格式修复
 * @param markdown
 * @returns {*}
 */
function fixMarkdownFormat(markdown) {
    let fixed = markdown;

    // 1. 修正标题格式：#后加空格，标题间强制换行
    // 先处理#后无空格的情况（在#和文字间加空格）
    fixed = fixed.replace(/#+(\S)/g, (match) => {
        const hashes = match.match(/#+/)[0]; // 提取所有#
        const text = match.slice(hashes.length); // 提取标题文字
        return `${hashes} ${text}`;
    });

    // 修正：在任意两个标题之间添加换行（包括隐藏在文本中的标题）
    // 使用更精确的正则来匹配标题模式（包括三级标题）
    fixed = fixed.replace(/([^#\n])(###? \*\*[^*]+\*\*)/g, '$1\n$2');
    fixed = fixed.replace(/([^#\n])(###? [^\n#]+)/g, '$1\n$2');

    // 处理连续标题的情况
    fixed = fixed.replace(/(#+ [^\n#]+)(#+ [^\n#]+)/g, '$1\n$2');

    // 2. 修正数字列表：确保每个数字列表项单独一行
    fixed = fixed.replace(/(\d+\.\s\*\*[^*]+\*\*[^0-9]+)(?=\d+\.)/g, '$1\n');

    // 3. 修正无序列表：确保每个列表项单独一行，-后有空格
    fixed = fixed.replace(/(\S)(-\s*\*\*)/g, '$1\n$2'); // 在列表项前加换行
    fixed = fixed.replace(/-\s*(\*\*)/g, '- $1'); // 确保-后有空格

    // 4. 修正块引用（>）：确保单独成行，前面有空行
    fixed = fixed.replace(/([^\n])(> \*\*)/g, '$1\n\n$2'); // 在块引用前加空行

    // 5. 修正表格：在表格前添加空行
    fixed = fixed.replace(/(\S)\s*(\|[^]+?\|\s*\|\s*[-|]+\s*\|)/, '$1\n\n$2');

    // 清理格式
    fixed = fixed.replace(/\n{3,}/g, '\n\n').trim();

    return fixed;
}


// 工具函数
function clearChart() {
    chartContainer.style.display = 'none';
    chartPlaceholder.style.display = 'flex';
    const chart = echarts.getInstanceByDom(chartContainer);
    if (chart) chart.dispose();
}

function showLoading(show) {
    loadingIndicator.classList.toggle('active', show);
}

function updateChartStatus(message, color) {
    chartStatus.textContent = message;
    if (color) chartStatus.style.color = color;
}

function showError(message) {
    errorArea.style.display = 'block';
    errorArea.innerHTML = `
        <strong>错误:</strong> ${message}
        <button onclick="errorArea.style.display='none'" style="margin-left: 10px; padding: 2px 8px; background: #e74c3c; color: white; border: none; border-radius: 3px; cursor: pointer;">
            关闭
        </button>
    `;
}

function clearError() {
    errorArea.style.display = 'none';
    errorArea.innerHTML = '';
}

function addDebugInfo(message) {
    debugArea.style.display = 'block';
    const timestamp = new Date().toLocaleTimeString();
    debugArea.innerHTML += `<div>[${timestamp}] ${message}</div>`;

    // 限制调试信息行数
    const lines = debugArea.innerHTML.split('</div>');
    if (lines.length > 15) {
        debugArea.innerHTML = lines.slice(-15).join('</div>') + '</div>';
    }

    debugArea.scrollTop = debugArea.scrollHeight;
}

function clearDebug() {
    debugArea.style.display = 'none';
    debugArea.innerHTML = '';
}